/*
	版权所有 2009-2021 荆门泽优软件有限公司
	保留所有权利
	官方网站：http://www.ncmem.com
	产品首页：http://www.ncmem.com/webapp/scp2/index.aspx
	控件下载：http://www.ncmem.com/webapp/scp2/pack.aspx
	示例下载：http://www.ncmem.com/webapp/scp2/versions.aspx
	联系邮箱：1085617561@qq.com
	联系QQ：1085617561
	版本：2.1.4
*/
function debugMsg(txt){$("#msg").append(txt+"<br/>");}

/*
	截屏对象管理类，提供常用配置功能
	参数
*/
function CaptureManager()
{
    //根路径：http://localhost:8888/
    var root = [
        window.location.protocol,
        "//",
        window.location.host,
        "/api/scp/"
    ].join("");

    //url=>res/
    //http://localhost:8888/scp/scp.js=>
    this.getJsDir = function () {
        var js = document.scripts;
        var jsPath;
        for (var i = 0; i < js.length; i++) {
            if (js[i].src.indexOf("scp.js") > -1) {
                jsPath = js[i].src.substring(0, js[i].src.indexOf("scp.js"));
            }
        }
        return jsPath;
    };
    //http://localhost/res/scp/
    var pathRoot = this.getJsDir();
    var pathRes = pathRoot + "imgs/";
    var pathPack = pathRoot + "pack/";

	var _this = this;
	this.scpFF = null;
    this.scpIE = null;
    this.pluginInited = false;
    this.ui = { panel: null, ico: null, img: null, msg: null, per: null ,setup:null};
    this.event = {
        postComplete: function (src) { }, hotKey: function () { }
    };
    this.data={
        editor:null,
        language:{
            en:{
                "CapForm": "Capture Form Selecter"
              , "CapFormTitle": "Choose Capture Form"
              , "CapFormTip": "Please set the window to the front which you want to intercept resize"
              , "BtnOk": "Ok"
              , "BtnCancel": "Cancel"
              , "RectSuze": "Rect Size"
              , "CurRGB": "Current RGB"
              , "QuckCap": "Double-click can be quickly completed Screenshot"
          },
            zh_cn:{
                "CapForm": "截屏选择窗口"
              , "CapFormTitle": "选择截屏窗口"
              , "CapFormTip": "请将您想要截取的窗口调整到最前"
              , "BtnOk": "确定"
              , "BtnCancel": "取消"
              , "RectSuze": "区域大小"
              , "CurRGB": "当前RGB"
              , "QuckCap": "双击可以快速完成截图"
          },
            zh_tw:{
                "CapForm": "截屏選擇視窗"
              , "CapFormTitle": "選擇截屏視窗"
              , "CapFormTip": "請將您想要截取的視窗調整到最前"
              , "BtnOk": "確定"
              , "BtnCancel": "取消"
              , "RectSuze": "區域大小"
              , "CurRGB": "當前RGB"
              , "QuckCap": "雙擊可以快速完成截圖"
          }
        },
        error:{
            "0": "就绪",
            "1": "发送数据错误",
            "2": "接收数据错误",
            "3": "域名未授权或为空",
            "4": "公司未授权或为空",
            "5": "nat app error"
        },
        state:{
            Ready : 0,
            Posting : 1,
            Stop : 2,
            Error : 3,
            GetNewID : 4,
            Complete : 5,
            WaitContinueUpload	: 6,
            None : 7,
            Waiting : 8
        }
    };

	//全局配置信息
	this.Config = {
		  "PostUrl"		: "http://www.ncmem.com/upload.aspx"
		, "EncodeType"	: "utf-8"
		, "Version"		: "1,4,75,45215"
		, "Company"		: "荆门泽优软件有限公司"
		, "License2"	: ""
        , "Debug"       : false//是否打开调试模式
        , "LogFile"     : "F:\\log.txt"//日志文件路径
        , "FileFieldName": "img"//自定义图片文件字段名称。
        , "ImageMatch"  : ""//服务器返回数据匹配模式，正则表达式，提取括号中的地址
        , "ImageUrl"    : ""//自定义图片地址，格式"{url}"，{url}为固定变量，在此变量前后拼接图片路径，此变量的值为posturl返回的图片地址
		, "LanCur"	    : this.data.language.zh_cn//语言设置
		, "Quality"     : 100//jpg图片质量，仅对jpg格式有效
		, "ShowForm"	: true//是否显示截屏提示窗口
		, "ImageType"	: "png"//图片上传格式。png,jpg,bmp
		, "NameCrypto"	: "crc"//名称生成算法。crc,md5,sha1,uuid
        , "IcoPath"     : pathRes+"upload.gif"
        , "Cookie"      : ""
        , "HotKey"      : "Ctrl+Alt+Q"
        , "Authenticate": { "type": "ntlm", "name": "", "pass": "" }//域环境信息
        , "UI": {
            selector: {
                border: "#DC143C"//选框边框
            },
            font: ["21", "22", "23", "24"],
            //文字特效：http://www.ncmem.com/doc/view.aspx?id=a7a1c09aac3b46a5996e32d562d4ae64
            text:{padding:13/*间距*/,background:"#FFA7CODC"/**背景色*/,border:"#FFE64340",round:8/**圆角大小*/,open:false/**打开功能*/}
        }
        //原始图片：http://www.ncmem.com/doc/view.aspx?id=06e3a01a60a84f8e968dd49a5a7c66e8
        , "Original": { name: "original", open: true }
        //x86
        , ie: {
            part: {
                clsid: "4E77CA71-574B-433D-9DA9-A1D47CC15810", name: "CABR.ScreenCapturePro2"
            }
            , path: pathPack + "scp.cab"
        }
        //x64
        , ie64: {
            part: {
                clsid: "48EFFCD1-417E-4EC7-A54D-1DD9CF290529", name: "CABR.ScreenCapturePro2x64"
            }
            , path: pathPack + "scp64.cab"
        }
        , firefox: { name: "", type: "application/npScpProCABR", path: "http://res2.ncmem.com/download/scp2/pack/2.1.12/scp.xpi" }
        , chrome: { name: "npScpProCABR", type: "application/npScpProCABR", path: "http://res2.ncmem.com/download/scp2/pack/2.1.12/scp.crx" }
	    //Chrome 45
        , chrome45: { name: "com.xproer.down2", path: "http://res2.ncmem.com/download/scp2/pack/2.1.12/scp.crx" }
        , exe: { path: pathPack + "scp.exe" }
        , edge: { protocol:"cabr",port:9800,visible:false}
        , "Fields": {"uname": "test","upass": "test","uid":"0","fid":"0"}
        , event:{}
    };

    if (arguments.length > 0) {
        var par = arguments[0];
        if (typeof (par.config) != "undefined") $.extend(true, this.Config, par.config);
        if (typeof (par.event) != "undefined") $.extend(true, this.event, par.event);
        if (typeof (par.ui) != "undefined") $.extend(true, this.ui, par.ui);
    }
    
	this.postError = function (json)
	{
	    this.ui.msg.html(
            this.data.error[json.value]+"<br/>"+
            "PostUrl:"+this.Config["PostUrl"]+"<br/>"+
            "License:"+this.Config["License"]+"<br/>"+
            "License2:"+this.Config["License2"]+"<br/>"+
            "当前Url:"+window.location.href);
	    this.ui.per.text("");
	};
	this.postProcess = function (json)
	{
	    this.ui.per.text(json.percent);
	};
	this.postComplete = function (json)
	{
	    this.ui.per.text("100%");
	    this.ui.msg.text("上传完成");
	    this.CloseMsg(); //隐藏信息层
        this.event.postComplete(json.value);
	};
	this.runComplete = function (json)
	{
	    this.Browser.exitCheck();
	};
    this.loadComplete = function (json) {
        this.pluginInited = true;
	    var needUpdate = true;
	    if (typeof (json.version) != "undefined") {
	        if (json.version == this.Config.Version) {
	            needUpdate = false;
	        }
	    }
        if (needUpdate) this.need_update();
        else { this.CloseMsg(); }
	};
    this.load_complete_edge = function (json) {
        this.pluginInited = true;
        this.edge_load = true;
        this.SafeCheck();
        this.CloseMsg();
	    _this.app.init();
	};
    this.afterCapture = function (json) { this.OpenMsg();/*打开信息面板*/ };
    this.hotKey = function (json) { this.event.hotKey(); }
    this.state_message = function (json) { alert(json.msg); }
	this.recvMessage = function (str)
	{
	    var json = JSON.parse(str);
	    if      (json.name == "AfterCapture") { _this.afterCapture(json); }
        else if (json.name == "HotKey") { _this.hotKey(json); }
        else if (json.name == "state_message") { _this.state_message(json); }
        else if (json.name == "post_process") { _this.postProcess(json); }
	    else if (json.name == "post_error") { _this.postError(json); }
	    else if (json.name == "post_complete") { _this.postComplete(json); }
	    else if (json.name == "run_complete") { _this.runComplete(json); }
	    else if (json.name == "run_error") { _this.postError(json); }
	    else if (json.name == "load_complete") { _this.loadComplete(json); }
	    else if (json.name == "load_complete_edge") { _this.load_complete_edge(json); }
	};
    
	var browserName = navigator.userAgent.toLowerCase();
	this.ie = browserName.indexOf("msie") > 0;
	//IE11
	this.ie = _this.ie ? _this.ie : browserName.search(/(msie\s|trident.*rv:)([\w.]+)/)!=-1;
	this.firefox = browserName.indexOf("firefox") > 0;
	this.chrome = browserName.indexOf("chrome") > 0;
	this.chrome45 = false;
    this.chrVer = navigator.appVersion.match(/Chrome\/(\d+)/);
    this.edge = navigator.userAgent.indexOf("Edge") > 0;
    this.edgeApp = new WebServer(this);
    this.app = scp_app;
    this.app.edgeApp = this.edgeApp;
    this.app.Config = this.Config;
    this.app.ins = this;
    if (this.edge) { this.ie = this.firefox = this.chrome = this.chrome45 = false; }

    this.pluginLoad = function () {
        if (!this.pluginInited) {
            if (this.edge) {
                this.edgeApp.connect();
            }
        }
    };
    this.pluginCheck = function () {
        if (!this.pluginInited) {
            alert("控件没有加载成功，请安装控件或等待加载。");
            this.pluginLoad();
            return false;
        }
        return true;
    };
    //Win64
    if (window.navigator.platform == "Win64")
    {
        jQuery.extend(this.Config.ie, this.Config.ie64);
    } //Firefox
    if (this.firefox)
    {
        this.edge = true;
        this.app.postMessage = this.app.postMessageEdge;
        this.edgeApp.run = this.edgeApp.runChr;
	} //chrome
	else if (this.chrome)
    {
        this.app.check = this.app.checkFF;
        jQuery.extend(this.Config.firefox, this.Config.chrome);
        this.edge = true;
        this.app.postMessage = this.app.postMessageEdge;
        this.edgeApp.run = this.edgeApp.runChr;
    }
    else if (this.edge)
    {
        this.app.postMessage = this.app.postMessageEdge;
    }

	this.GetHtml = function ()
	{
        //ff
        var html = "";
        //ie
	    //html += '<div style="display: none">';
	    html += '<object name="scpIE" classid="clsid:' + this.Config.ie.part.clsid + '"';
	    html += ' codebase="' + this.Config.ie.path + '#version=' + this.Config["Version"] + '" width="1" height="1"></object>';
        if (this.edge) html = '';
	    //html += '</div>';
	    //
        html += '<div name="ui-scp" class="panel-scp">\
	                <img name="ico" alt="进度图标" src="/scp/upload.gif" /><span name="msg">图片上传中...</span><span name="per">10%</span>\
	            </div>';
        //安装提示
        html += '<div name="ui-setup" class="panel-scp panel-setup"></div>';
	    return html;
	};


    //安全检查，在用户关闭网页时自动停止所有上传任务。
    this.SafeCheck = function (event) {
        //$(window).bind("beforeunload", function (event) {});
        $(window).bind("unload", function () {
            if (this.edge) _this.edgeApp.close();
        });
    };
	this.setup_tip = function ()
    {
        this.ui.setup.skygqbox();
        var dom = this.ui.setup.html("控件加载中，如果未加载成功请先<a name='w-exe'>安装控件</a>");
        var lnk = dom.find('a[name="w-exe"]');
        lnk.attr("href", this.Config.exe.path);
    };
    this.need_update = function () {
        var dom = this.ui.setup.html("发现新版本，请<a name='w-exe' href='#'>更新</a>");
        var lnk = dom.find('a[name="w-exe"]');
        lnk.attr("href", this.Config.exe.path);
    };

    //加载到document.body中
	this.loadAuto= function()
	{
        if(!ScreenCapture.inited)
        {
            var ui = $(document.body).append(this.GetHtml());
            this.initUI(ui);
        }
        ScreenCapture.inited = true;
        return this;
    };
	
	//加截到指定对象内部
	this.load_to = function(o)
	{
        if(!ScreenCapture.inited)
        {
            var ui = o.append(this.GetHtml());
            this.initUI(ui);
        }
        ScreenCapture.inited = true;
        return this;
    };

    this.initUI = function (ui)
    {
        this.parter = ui.find('embed[name="scpFF"]').get(0);
        this.scpIE = ui.find('object[name="scpIE"]').get(0);
        this.ui.panel = ui.find('div[name="ui-scp"]');
        this.ui.ico = ui.find('img[name="ico"]').attr("src", this.Config["IcoPath"]);
        this.ui.msg = ui.find('span[name="msg"]');
        this.ui.per = ui.find('span[name="per"]');
        this.ui.setup = ui.find('div[name="ui-setup"]');

        $(function () {
            if (!_this.edge) {
                if (_this.ie) {
                    _this.parter = _this.scpIE;
                }
                _this.parter.recvMessage = _this.recvMessage;
            }
            _this.setup_tip();
            if (_this.edge) {
                _this.edgeApp.connect();
            }
            else {
                _this.app.init();
            }
        });
    };

	//截屏函数
    this.Capture = function () {
        if (!this.pluginCheck()) return;
        var opt = { autoHide: false};//自动隐藏当前窗口
        this.app.capture(opt);
    };
    this.Capture2 = function () {
        if (!this.pluginCheck()) return;
        var opt = { form: this.Config.ShowForm };//不显示提示窗口
        this.app.capture(opt);
    };
    //自动隐藏当前窗口
    this.CaptureHide = function () {        
        if (!this.pluginCheck()) return;
        var opt = { autoHide: true };//自动隐藏当前窗口
        this.app.capture(opt);};

    /**
     * 截取整个屏幕
     * @param bool edit 是否启动编辑
     */
    this.CaptureScreen = function (edit)
    {
        if (!this.pluginCheck()) return;
        this.app.captureScreen({"edit":edit});
    };
	//截取指定区域
    this.CaptureRect = function (x, y, w, h)
    {
        if (!this.pluginCheck()) return;
        this.app.captureRect(x, y, w, h);
    };
    this.OpenMsg = function () {
        _this.ui.panel.skygqbox();	    
	    _this.ui.msg.text("图片上传中...");
    };
    this.Paste = function () {
        if (!this.pluginCheck()) return;
        this.app.paste();
    };
    this.CloseMsg = function () { $.skygqbox.hide(); };

    //加载
    if (typeof (this.ui.render) == "string") {
        $(function () {
            _this.load_to($("#" + _this.ui.render));
        })
    }
    else if (typeof (this.ui.render) == "object") {
        this.load_to(this.ui.render);
    }
}
//用法：
/**
 * ScreenCapture.getInstance().loadAuto();
 */
var ScreenCapture={
    instance:null,
    inited:false,
    getInstance:function(cfg){
        if (this.instance == null) {
            this.instance = new CaptureManager(cfg);
        }
        return this.instance;
    }
};